package com.keyancompany.zhongbaopingtai.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.api.FileAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.photoselector.util.CommonUtils;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.OnClick;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import kankan.wheel.activity.CitiesActivity;

public class RealNameCompanyActivity extends BaseActivity {

    private static final int RESULT_CODE = 1314;
    private static final int LOGO_CODE = 311;
    private static final int HADLE_CODE = 312;

    @BindString(R.string.company_author_text)
    String title;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.chinese_name)
    EditText chineseName;
    @Bind(R.id.english_name)
    EditText englishName;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.origin_code)
    EditText originCode;
    @Bind(R.id.phone)
    EditText phone;
    @Bind(R.id.chuanzhen)
    EditText chuanzhen;
    @Bind(R.id.activity_real_name_company)
    LinearLayout activityRealNameCompany;
    @Bind(R.id.rigester_moeny)
    EditText rigesterMoeny;
    @Bind(R.id.logo_card)
    ImageView logoCard;
    @Bind(R.id.logo_card_delete)
    ImageView logoCardDelete;
    @Bind(R.id.logo_card_progress)
    SmoothProgressBar logoCardProgress;
    @Bind(R.id.logo_card_upload_error)
    TextView logoCardUploadError;
    @Bind(R.id.hadle_id_card)
    ImageView hadleIdCard;
    @Bind(R.id.hadle_id_card_delete)
    ImageView hadleIdCardDelete;
    @Bind(R.id.hadle_id_card_progress)
    SmoothProgressBar hadleIdCardProgress;
    @Bind(R.id.hadle_id_card_upload_error)
    TextView hadleIdCardUploadError;

    private Intent data;
    String province;
    String city;
    String district;
    private String[] papers_pic = new String[2];

    @Override
    protected int getContentViewId() {
        return R.layout.activity_real_name_company;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, title);
    }

    @Override
    protected void setUpViews() {

    }


    @OnClick(R.id.address)
    public void addressSelect(View view) {
        CitiesActivity.buildIntent(this, data, RESULT_CODE);
    }

    @OnClick(R.id.logo_card) //logo
    public void selecLogoPhoto(View view) {
        if(logoCardProgress.getVisibility() == View.VISIBLE || logoCardDelete.getVisibility() == View.VISIBLE){
            return ;
        }
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, LOGO_CODE, 1);
    }

    @OnClick(R.id.hadle_id_card) //营业执照电子版
    public void selectHadlePhoto(View view) {
        if(hadleIdCardProgress.getVisibility() == View.VISIBLE || hadleIdCardDelete.getVisibility() == View.VISIBLE){
            return ;
        }
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, HADLE_CODE, 1);
    }

    @OnClick(R.id.submit_auther) //提交
    public void ToPayPassword(View view) {
        String chinese = chineseName.getText().toString();
        if (TextUtils.isEmpty(chinese)) {
            T.show(this, "请输入企业中文名称", Toast.LENGTH_SHORT);
            return;
        }
        String english = englishName.getText().toString();
        if (TextUtils.isEmpty(english)) {
            T.show(this, "请输入企业英文名称", Toast.LENGTH_SHORT);
            return;
        }
        String origin = originCode.getText().toString();

        String money = rigesterMoeny.getText().toString();
        if (TextUtils.isEmpty(money)) {
            T.show(this, "请输入注册资本", Toast.LENGTH_SHORT);
            return;
        }
        String phoneStr = phone.getText().toString();
        if (TextUtils.isEmpty(phoneStr)) {
            T.show(this, "请输入联系电话", Toast.LENGTH_SHORT);
            return;
        }
        String czhenStr = chuanzhen.getText().toString();
        if (TextUtils.isEmpty(czhenStr)) {
            T.show(this, "请输入联系传真", Toast.LENGTH_SHORT);
            return;
        }
        String addressStr = address.getText().toString();
        if(validatePic()){
            T.show(this, "请确认图片上传完毕 !", Toast.LENGTH_SHORT);
            return ;
        }

        UserAPI.attestationFirm(chinese, english, origin, papersValue, money, null, phoneStr, czhenStr,
                province, city, district, addressStr, this, getLoading(-1));
    }

    String papersValue ;
    private boolean validatePic(){
        papersValue = "{";
        for(int i = 0 ; i < papers_pic.length ; i++){
            if(TextUtils.isEmpty(papers_pic[i])){
                return true;
            }
            papersValue+= papers_pic[i];
            if(i != papers_pic.length-1){
                papersValue+=",";
            }
        }
        papersValue+="}";
        return false;
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        if (base.isSuccess()) {
            finish();
        }else{
            T.showShort(RealNameCompanyActivity.this,base.msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CODE && resultCode == RESULT_OK) {
            this.data = data;
            province = data.getStringExtra("provinceName");
            city = data.getStringExtra("cityName");
            district = data.getStringExtra("areaName");
            address.setText(province + "、" + city + "、" + district);
        }
        if (resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {

                if (requestCode == LOGO_CODE) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                            .getSerializable("photos");
                    if (photos == null || photos.isEmpty())
                        return;
                    ImageLoader.getInstance().displayImage("file:///" + photos.get(0).getOriginalPath(), logoCard);
                    uploadFile(0,logoCard,new File(photos.get(0).getOriginalPath()),logoCardDelete,logoCardProgress,logoCardUploadError);
                } else if (requestCode == HADLE_CODE) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                            .getSerializable("photos");
                    if (photos == null || photos.isEmpty())
                        return;
                    ImageLoader.getInstance().displayImage("file:///" + photos.get(0).getOriginalPath(), hadleIdCard);
                    uploadFile(1,hadleIdCard,new File(photos.get(0).getOriginalPath()),hadleIdCardDelete,hadleIdCardProgress,hadleIdCardUploadError);
                }
            }
        }
    }


    public void uploadFile(final int position,final ImageView iv, final File file , final ImageView delete , final SmoothProgressBar progressBar , final TextView uploadError){
        uploadError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FileAPI.uploadFile(file, new FileIAsyncHttpResponseHandler(position, delete, progressBar, uploadError), null);
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv.setImageResource(R.mipmap.ic_auth_weixin);
                delete.setVisibility(View.GONE);
                uploadError.setVisibility(View.GONE);
                progressBar.setVisibility(View.GONE);
                papers_pic[position] = null;
            }
        });
        FileAPI.uploadFile(file, new FileIAsyncHttpResponseHandler(position ,delete, progressBar, uploadError) ,null);
    }


    public class FileIAsyncHttpResponseHandler implements IAsyncHttpResponseHandler {
        ImageView delete ;
        SmoothProgressBar progressBar ;
        TextView uploadError;
        int position ;
        public FileIAsyncHttpResponseHandler(int position,ImageView delete, SmoothProgressBar progressBar, TextView uploadError) {
            this.delete = delete;
            this.progressBar = progressBar;
            this.uploadError = uploadError;
            this.position = position;
        }
        @Override
        public void start(int type) {
            progressBar.setVisibility(View.VISIBLE);
            delete.setVisibility(View.GONE);
            uploadError.setVisibility(View.GONE);
        }

        @Override
        public void success(int type, String json) {
            progressBar.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
            uploadError.setVisibility(View.GONE);

            BaseModel base = validateJson(json);
            if(base.isSuccess()) {
                JSONObject jsonObject = JSONObject.parseObject(base.data);
                papers_pic[position] = jsonObject.getString("pid");
            }else{

            }
        }

        @Override
        public void failed(String error) {
            uploadError.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
        }

        @Override
        public void finish(int type) {

        }
    }

}
